package com.hubujun.driverlicense.util;

import android.content.Context;
import android.text.Html;
import android.text.Spanned;
import android.widget.EditText;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TextUtils {

    public static final long REFRESH_DELAY_TIME = 200;

    private static final Pattern mEmotionPattern = Pattern.compile("\\(([a-zA-Z0-9\u4e00-\u9fbb!\\?]+)\\)");

    private TextUtils() {
    }

    /**
     * 获得一个edittext控件内容
     *
     * @param edittext
     * @return
     */
    public static String getEditTextContent(EditText edittext) {
        String s = edittext.getText().toString().trim();
        if (s.length() == 0)
            s = null;
        return s;
    }

    public static String getStringFromRaw(Context context, int resId) throws Exception {
        InputStream inputstream = context.getResources().openRawResource(resId);
        BufferedReader in = new BufferedReader(new InputStreamReader(inputstream, "gbk"));
        StringBuffer buffer = new StringBuffer();
        String line = "";
        while ((line = in.readLine()) != null) {
            buffer.append(line);
        }
        return buffer.toString();

    }

    public static String newLineToBr(String s) {
        return s.replaceAll("\n", "  ");
    }

    public static int getCharacterLength(String string) {
        if (isNullOrEmpty(string)) {
            return 0;
        }
        byte[] bytes;
        try {
            bytes = string.getBytes("UTF-8");
            return bytes.length;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * @param strcon   要查询的 字符串
     * @param strArray 所在的 字符串数组
     * @return
     */
    public static boolean checkIFContainStr(String strcon, String[] strArray) {
        boolean ret = false;
        if (strcon != null && strArray != null) {
            for (String str : strArray) {
                if (strcon.equals(str)) {
                    ret = true;
                    break;
                }
            }
        }
        return ret;
    }

    public static boolean isEmpty(String str) {
        if (str != null && str.length() > 0)
            return false;
        else
            return true;
    }

    public static boolean isNullOrEmpty(String str) {
        if (str != null && str.length() > 0)
            return false;
        else
            return true;
    }

    public static String getValibText(String str) {
        return getValibText(str, "");
    }

    public static String getValibText(String str, String defaultString) {
        if (isNullOrEmpty(str))
            return defaultString;
        return str;
    }

    public static String getDistanceText(long distance) {
        String showtxt = "1米";
        if (distance >= 100000) {
            showtxt = "100千米";
            int dis = (int) (distance / 1000);
            showtxt = new StringBuffer().append(dis).append("千米").toString();
        } else if (distance >= 1000) {
            showtxt = "1千米";
            DecimalFormat fnum = new DecimalFormat("##0.00");
            float dis = distance * 1f / 1000;
            showtxt = new StringBuffer().append(fnum.format(dis)).append("千米").toString();
        } else if (distance > 0) {
            showtxt = new StringBuffer().append(distance).append("米").toString();
        } else {
            showtxt = "1米";
        }
        return showtxt;
    }

    public static String getAccountID(long id) {
        return new StringBuffer().append(id).toString();
    }

    public static String append(String lstr, String rstr) {
        StringBuffer sbf = new StringBuffer();
        if (!isNullOrEmpty(lstr))
            sbf.append(lstr);
        if (!isNullOrEmpty(rstr))
            sbf.append(rstr);
        return sbf.toString();
    }

    public static String getUnreadMsgString(int count) {
        if (count < 99) {
            return String.valueOf(count);
        } else {
            return "99";
        }
    }

    /**
     * 检查参数是否手机号码格式
     *
     * @param mobile
     * @return
     */
    public static boolean isMobile(String mobile) {
        Pattern MOBILE_TEMPLATE = Pattern.compile("13\\d{9}|15\\d{9}|18\\d{9}");
        return isValidPattern(mobile, MOBILE_TEMPLATE);
    }

    /**
     * 根据提交的pattern检查是否符合正则表达式。 注：此方法限制给出的字符串必须是数字、英文字母或中文字符
     *
     * @param text
     * @param pattern
     * @return
     */
    public static boolean isValidPattern(String text, Pattern pattern) {
        if (!isNumeric(text)) {
            return false;
        }

        if (pattern == null)
            return false;

        Matcher regexp = pattern.matcher(text);
        if (!regexp.matches()) {
            return false;
        }
        return true;
    }

    /**
     * 检查字符串中是否每一个字符是数字
     *
     * @param text
     * @return
     */
    public static boolean isNumeric(String text) {
        if (text == null)
            return false;
        boolean result = true;
        for (int i = 0; i < text.length(); i++) {
            if (!Character.isDigit(text.charAt(i))) {
                result = false;
                break;
            }
        }
        return result;
    }

    /**
     * 获取带颜色的字符串
     *
     * @param colorvalue
     * @param srcText    需要设置颜色的文字
     * @param preText    不需要上色的前部分
     * @param suffixText 不需要上色的后部分
     * @return
     */
    public static Spanned getTextWithColor(String colorvalue, Object srcText, String preText, String suffixText) {
        if (srcText == null) {
            return null;
        }
        if (preText == null) {
            preText = "";
        }
        if (suffixText == null) {
            suffixText = "";
        }
        return Html.fromHtml(preText + "<font color=\"" + colorvalue + "\">" + srcText + "</font>" + suffixText);
    }

    /**
     * MM:SS 字串如 18:44 = 18分44秒
     *
     * @param time 毫秒
     * @return
     */
    public static String getMMSSString(long time) {
        return String.format("%02d:%02d", time / 60, time % 60);
    }

    public static String getHHMMSSString(long time) {
        if (time >= 3600) {
            return String.format("%02d:%02d:%02d", time / 3600, (time % 3600) / 60, time % 60);
        }
        return getMMSSString(time);
    }

    public static String getDefaultRecordName(long time) {
        return new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(time);
    }

    public static String formatTime(long startTime, long endTime) {
        Ln.d("TextUtils formatTime startTime=%s,endTime=%s", startTime, endTime);
        Date start = new Date(startTime);
        Date end = new Date(endTime);
        SimpleDateFormat sdf = new SimpleDateFormat("M月d日 HH:mm");
        SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm");
        return sdf.format(start) + " - " + sdf1.format(end);
    }

    public static String bytes2String(byte[] bytes) {
        if (bytes != null && bytes.length > 0) {
            StringBuffer sbf = new StringBuffer();
            sbf.append("[");
            for (int i = 0; i < bytes.length; i++) {
                String hex = Integer.toString(bytes[i] & 0xff);
                if (hex.length() == 1) {
                    hex = '0' + hex;
                }
                sbf.append(hex);
                if (i < (bytes.length - 1)) {
                    sbf.append(",");
                }
            }
            sbf.append("]");
            return sbf.toString();
        }
        return "";
    }

    /**
     * 获取 文件大小字符串
     *
     * @param size
     * @return
     */
    public static String fileSizeString(long size) {
        if (size >= 1073741824L) {
            return String.format("%.1fGB", ((double) size) / 1073741824L);
        } else if (size >= 1048576L) {
            return String.format("%.1fMB", ((double) size) / 1048576L);
        } else {
            return String.format("%.1fKB", ((double) size) / 1024L);
        }
    }

    /**
     * 格式化
     *
     * @param phoneStr
     */
    public static String formatPhoneNumer(String phoneStr) {
        if (TextUtils.isNullOrEmpty(phoneStr)) {
            return phoneStr;
        }

        if (phoneStr.contains("-")) {
            phoneStr = phoneStr.substring(phoneStr.indexOf("-") + 1);
        }
        Ln.d("TextUtils phoneStr=%s", phoneStr);
        int length = phoneStr.length() / 3;
        String c = "";
        for (int i = 0; i < phoneStr.length() - 2 * length; i++) {
            c += "*";
        }
        phoneStr = phoneStr.substring(0, length) + c + phoneStr.substring(phoneStr.length() - length);

        return phoneStr;
    }
}
